package com.cscec81.passport.base.cas.configuration;


import cn.hutool.core.codec.Base64;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
import org.springframework.security.web.savedrequest.HttpSessionRequestCache;
import org.springframework.security.web.savedrequest.RequestCache;
import org.springframework.security.web.savedrequest.SavedRequest;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;

@Slf4j
@Service
public class CasAuthenticationSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler {
  private RequestCache requestCache = new HttpSessionRequestCache();

  @Resource
  private CasProperties casProperties;

  @Override
  public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws ServletException, IOException {
    SavedRequest savedRequest = this.requestCache.getRequest(request, response);
    if (savedRequest == null) {
      HttpSession session = request.getSession(false);

      log.info("登录成功开始跳转----savedRequest--------------------------------");
      String referer = casProperties.getDefaultRedirectUrl();
      if (session != null) {
        log.info("sessionId: {}", session.getId());
        referer = referer+"?sessionId3="+ Base64.encode(session.getId());

        Cookie cookie = new Cookie("SESSION", Base64.encode(session.getId()));
        response.addCookie(cookie);
        response.setHeader("Set-Cookie", "SESSION="+Base64.encode(session.getId()));
      }

      log.info("referer: {}", request.getHeaders("referer"));
      log.info("all: {}", request.toString());

      this.clearAuthenticationAttributes(request);
      this.getRedirectStrategy().sendRedirect(request, response, referer);
    } else {
      log.info("登录成功开始跳转------------------------------------------------");
      String targetUrlParameter = this.getTargetUrlParameter();
      if (!this.isAlwaysUseDefaultTargetUrl() && (targetUrlParameter == null || !StringUtils.hasText(request.getParameter(targetUrlParameter)))) {
        log.info("step1");
        this.clearAuthenticationAttributes(request);
        String targetUrl = casProperties.getDefaultRedirectUrl();
//        String targetUrl = savedRequest.getRedirectUrl();

//        List<String> referer = savedRequest.getHeaderValues("referer");
//        log.info("step1 referer {}", referer);
//        if (!referer.isEmpty()) {
//          targetUrl = referer.get(0);
//        }
        log.info("step1 targetUrl {}", targetUrl);
        this.getRedirectStrategy().sendRedirect(request, response, targetUrl);
      } else {
        log.info("step2 {}", this.isAlwaysUseDefaultTargetUrl());
        log.info("step3 {}", targetUrlParameter);
        log.info("step4 {}", request.getParameter(targetUrlParameter));

        requestCache.removeRequest(request, response);
        super.onAuthenticationSuccess(request, response, authentication);
      }
    }
  }

  public void setRequestCache(RequestCache requestCache) {
    this.requestCache = requestCache;
  }
}
